package com.upload;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @program: servlet
 * @description:
 * @author: Dawson.Zhang
 * @create: 2020-03-12
 **/
public class AStudyUpload extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        enctype="multipart/form-data"发送的数据是流的形式，必须要流来接受
//        String userName = req.getParameter("userName");
//        System.out.println(userName);
//        使用流的形式来接受数据（整个请求体的数据）
//        ------WebKitFormBoundaryZsMiZ4OKAWZLMKlW
//        Content-Disposition: form-data; name="userName"
//
//        123
//            ------WebKitFormBoundaryZsMiZ4OKAWZLMKlW
//        Content-Disposition: form-data; name="photo"; filename="a.jpg"
//        Content-Type: image/jpeg
//        ServletInputStream inputStream = req.getInputStream();
//        BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
//        byte [] bytes = new byte[1024];
//        int leng;
//        while ((leng=bufferedInputStream.read(bytes))!=-1){
//            System.out.println(new String(bytes,0,leng));
//        }
//        System.out.println("文件上传过来了");
       FileItemFactory fileItemFactory = new DiskFileItemFactory();
       ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
        try {
            List<FileItem> list = servletFileUpload.parseRequest(req);
            for (FileItem fileItem : list) {
                if (fileItem.isFormField()) {
                    // 获取文本框 name 属性值
                    System.out.println(fileItem.getFieldName());
                    // 获取name属性对应的value值
                    System.out.println(fileItem.getString());
                }else{
                    // 获取name属性值
                    System.out.println(fileItem.getFieldName());
                    // 获取文件名
                    System.out.println(fileItem.getName());
                    fileItem.write(new File("D:\\11\\"+fileItem.getName()));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
